const express = require('express');
const router = express.Router();

const PackagePrisma = require('../models/PackagePrisma');
const { authenticateToken } = require('../middleware/auth');
const ResponseHelper = require('../utils/response');

/**
 * 接口 8: 获取套餐列表
 * GET /api/v1/packages
 *
 * 查询 packages 表中所有上架的套餐
 */
router.get('/', async (req, res) => {
  try {
    const { type } = req.query;

    let packages;
    if (type) {
      // 根据类型获取套餐
      packages = await PackagePrisma.findActivePackagesByType(type, {
        orderBy: { sort_order: 'asc' }
      });
    } else {
      // 获取所有套餐
      packages = await PackagePrisma.findActivePackages({
        orderBy: { sort_order: 'asc' }
      });
    }

    ResponseHelper.success(res, {
      items: packages.map(pkg => pkg.toJSON()),
      total: packages.length
    }, '获取套餐列表成功');

  } catch (error) {
    console.error('获取套餐列表错误:', error);
    ResponseHelper.serverError(res, '获取套餐列表失败', error);
  }
});

/**
 * 根据ID获取套餐详情
 * GET /api/v1/packages/:id
 */
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const packageData = await PackagePrisma.findById(id);
    if (!packageData) {
      return ResponseHelper.notFound(res, '套餐不存在');
    }

    ResponseHelper.success(res, {
      package: packageData.toJSON()
    }, '获取套餐详情成功');

  } catch (error) {
    console.error('获取套餐详情错误:', error);
    ResponseHelper.serverError(res, '获取套餐详情失败', error);
  }
});

module.exports = router;
